<template>
  <a-form-model ref="userForm" layout="vertical" :model="form" :rules="rules">
    <a-form-model-item label="" style="margin: 0;display: none">
      <a-input v-model="form.employeeCode" placeholder="" style="display: none" />
    </a-form-model-item>
    <a-form-model-item label="" style="margin: 0;display: none">
      <a-input v-model="form.a0102Name" placeholder="" style="display: none" />
    </a-form-model-item>
    <a-form-model-item label="" style="margin: 0;display: none">
      <a-input v-model="form.a0103Name" placeholder="" style="display: none" />
    </a-form-model-item>
    <a-form-model-item label="" style="margin: 0;display: none">
      <a-input v-model="form.a0104Name" placeholder="" style="display: none" />
    </a-form-model-item>
    <a-row :gutter="8"  v-if="!editFlag">
      <a-col :span="24">
        <a-form-model-item label="搜索人员">
          <a-select
              show-search
              :value="value"
              placeholder="请输入姓名"
              :default-active-first-option="false"
              :show-arrow="false"
              :filter-option="false"
              :not-found-content="fetching ? undefined : null"
              @search="handleSearch"
              @change="handleChange"
              @select="personSelect"

          >
            <a-spin v-if="fetching" slot="notFoundContent" size="small" />
            <a-select-option v-for="(user, index) in userList" :key="user.employeeCode">
              {{ user.fullName + ':' +user.a0106 }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row :gutter="8"  v-if="!editFlag">
      <a-col :span="24">
        <a-form-model-item label="选择人员">
          <a-cascader
                      :options="options"
                      :load-data="loadData"
                      placeholder="请选择"
                      change-on-select
                      @change="onChange"
          />
<!--          <a-input v-else v-model="form.userName" placeholder="" disabled/>-->
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row :gutter="24">
      <a-col :span="12">
        <a-form-model-item label="用户姓名">
          <a-input v-model="form.fullName" placeholder="" disabled/>
        </a-form-model-item>
      </a-col>
    </a-row>
<!--    <a-row :gutter="24">-->
<!--      <a-col :span="12">-->
<!--        <a-form-model-item label="所属机构">-->
<!--          <a-input v-model="form.a0102Name" placeholder="" disabled/>-->
<!--        </a-form-model-item>-->
<!--      </a-col>-->
<!--      <a-col :span="12">-->
<!--        <a-form-model-item label="所属科室">-->
<!--          <a-input v-model="form.a0103Name" placeholder="" disabled/>-->
<!--        </a-form-model-item>-->
<!--      </a-col>-->
<!--    </a-row>-->
    <a-row :gutter="24">
      <a-col :span="24">
        <a-form-model-item label="职务">
          <a-input v-model="form.a0104Name" placeholder="" disabled/>
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row :gutter="24">
      <a-col :span="24">
        <a-form-model-item label="所属部门">
          <a-input v-model="form.a0106" placeholder="" disabled/>
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row :gutter="24">
      <a-col :span="24">
        <a-form-model-item label="管理区域（可多选）" prop="userOrgIds">
          <a-tree-select
              v-model="form.userOrgIds"
              style="width: 100%"
              :tree-data="orgTreeData"
              tree-checkable
              :show-checked-strategy="SHOW_PARENT"
              search-placeholder="请选择"
              @change="onChangeTree"
          />
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row :gutter="24" v-for="(item, index) in form.permissionGroup" :key="index">
      <a-col :span="8">
        <a-form-model-item style="margin-bottom: 0px;" :label="index===0 ? '角色':''" :key="'role_'+index" prop="a0202">
          <a-select v-model="form.permissionGroup[index].a0202" placeholder="请选择" @change="handleChangeA0202(index,$event)">
            <a-select-option v-for="(item) in a0202DictList" :key="item.dictKey" :value="item.dictKey" :disabled="item.status==='0'">
              {{item.dictValue}}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>
      <a-col :span="16">
        <a-form-model-item class="custom" style="margin-bottom: 0px;" :label="index===0 ? '权限配置（可多选）':''" :key="'permission_'+index">
          <a-input style="width: 291px" v-if="['all','allAndPartSystem'].indexOf(form.permissionGroup[index].objectIds) > -1" v-model="form.permissionGroup[index].label" placeholder="" disabled/>
          <a-tree-select v-else
              ref="permission"
              v-model="form.permissionGroup[index].objectIds"
              :tree-data="busiRouterTreeData"
              tree-checkable
              :show-checked-strategy="SHOW_CHILD"
              search-placeholder="请选择"
              :disabled="form.permissionGroup[index].disabled!==undefined"
          />
          <a-icon
              v-if="form.permissionGroup.length > 1"
              class="dynamic-delete-button"
              type="minus-circle-o"
              :disabled="form.permissionGroup.length === 1"
              @click="removePermission(item)"
          />
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row :gutter="24" v-if="form.permissionGroup.length < length">
      <a-col :span="24">
        <a-button type="dashed" style="width: 100%" @click="addBusiRole">
          <a-icon type="plus" /> 新增角色
        </a-button>
      </a-col>
    </a-row>
    <a-row :gutter="24">
      <a-col :span="24">
        <a-form-model-item label="驾驶舱权限">
          <a-input v-model="form.fieldA" placeholder="请选择" />
        </a-form-model-item>
      </a-col>
    </a-row>
  </a-form-model>
</template>
<script>
import {getOrgOrUserInZzd,getOrgTreeDataByPermission,getRoleParamsByOrg,getOperateRouterTree,getOrgOrUserInZzdForLocal,getUserDetailInfoInZzd,getUserListInZzd} from '@/services/system/whdngxlApi'
import {getBatchDict} from "@/services/system/api"
import { TreeSelect } from 'ant-design-vue';
const SHOW_PARENT = TreeSelect.SHOW_PARENT;
const SHOW_CHILD = TreeSelect.SHOW_CHILD;
export default {
  props: {
    userInfo: {
      type: Object,
      default: () => {},
      required: false
    }
  },
  data() {
    return {
      fetching: false,
      userList: [],
      rules: {
        userName: [{ required: true, message: '请选择人员', trigger: 'blur' }],
      },
      options: [],
      form: {
        //sys_user表数据
        userId: '',
        employeeCode: '',
        userName: '',
        fullName: '',
        userType: '10',
        status: '1',
        //a01表数据
        a0102: '',
        a0102Name: '',
        a0103: '',
        a0103Name: '',
        a0104: '',
        a0104Name: '',
        a0105: '',
        a0106: '',
        //a02表数据+a03表数据
        permissionGroup: [{
          a0202: null,//人员类型
          objectType: 'router',//权限类型
          objectIds: [],//权限id
        }],
        //数据权限
        userOrgIds: [],
      },
      //路由权限
      routerPermission: [
        {
          routerId: '1',
          key: '',
          title: ''
        }
      ],
      busiRouterTreeData: [],
      SHOW_PARENT,
      SHOW_CHILD,
      orgTreeData: [],
      a0202DictList: [],
      a0202DictListTemp: [],
      editFlag: false,
      a0202SelectList: [],
      beforeOrgId: null,
      length: 0,
      timer: null
    };
  },
  created() {
    this.$http.post(getOrgTreeDataByPermission, {}).then(res => {
      this.orgTreeData = res.result.orgList
      if(this.userInfo){
        this.editFlag = true
        this.form = JSON.parse(JSON.stringify(this.userInfo))
        this.$http.post(getRoleParamsByOrg, {orgId: this.form.userOrgIds[0]}).then(res => {
          this.a0202DictList = res.result
          this.beforeOrgId = this.form.userOrgIds[0]
          if(this.beforeOrgId === '330300000000'){
            this.length = 1
          }else {
            this.length = this.a0202DictList.length
          }


          debugger
          this.form.permissionGroup.forEach((item,index) =>{
            if(item.a0202){
              if(this.a0202SelectList[index]){
                this.a0202SelectList.splice(index,1,{index,value: item.a0202})
              }else {
                this.a0202SelectList.push({index,value: item.a0202})
              }
            }
            if(['00','01'].indexOf(item.a0202) > -1){
              this.form.permissionGroup[index].disabled = true
              if(item.a0202 === '01'){
                this.form.permissionGroup[index].objectIds = 'all'//所有模块权限
                this.form.permissionGroup[index].label = '所有业务模块权限'
                this.length = 1
              }else {
                this.form.permissionGroup[index].objectIds = 'allAndPartSystem'
                this.form.permissionGroup[index].label = '所有业务模块及部分系统权限'
                this.length = 1
              }
            }else if(['02','03','04'].indexOf(item.a0202) > -1){
              this.form.permissionGroup[index].disabled = undefined
              const params = {
                userType: item.a0202,
              }
              this.$http.post(getOperateRouterTree, params).then(res => {
                this.busiRouterTreeData = res.result
              })
            }
          })
        })
      }
    })

    if(!this.userInfo){
      //实际是调取浙政钉的接口
      this.$http.post(getOrgOrUserInZzd, {searchOrg: true}).then(res => {
        this.options = res.result
        this.options.forEach(item =>{
          item.isLeaf = item.leaf
        })
      })
    }

  },
  methods:{
    // 树节点选择事件
    personSelect(value) {
      console.log("select=====" + value)
      // this.$emit('select', value)
    },
    handleSearch(value) {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      if (value.length >= 2) {
        console.log("handleSearch=====" + value)
        this.timer = setTimeout(() => {
          this.onSearch(value, data => {
            this.userList = data
          });
        }, 500)
      }
    },
    handleChange(value) {
      console.log("handleChange=====" + value)
      this.value = value
      for (const userListElement of this.userList) {
        if(userListElement.employeeCode === value){
          Object.assign(this.form, userListElement)
          this.$http.post(getUserDetailInfoInZzd, {employeeCode: userListElement.employeeCode,organizationCode: userListElement.organizationCode}).then(res => {
            this.form.a0104Name = res.result.a0104Name
          })
          break
        }
      }
    },
    //查询模糊列表
    onSearch(value, callback) {
      console.log("onSearch=====" + value)
      this.userList = []
      this.fetching = true;
      this.$http.post(getUserListInZzd, {fullName: value}).then((res) => {
        callback(res.result);
        this.fetching = false;
      }).catch(() => {
        modal.warn({title: '警告提示', content: '查询异常'})
        this.fetching = false;
      })
    },
    onChange(value,selectedOptions) {
      const lastItem = value[value.length - 1]
      if(lastItem.indexOf('GE_') > -1){
        const targetOption = selectedOptions[selectedOptions.length - 1];
        this.form.fullName = targetOption.employeeName
        this.$http.post(getUserDetailInfoInZzd, {employeeCode: lastItem,organizationCode: selectedOptions[selectedOptions.length - 2].organizationCode}).then(res => {
          console.log(this.form)
          Object.assign(this.form, res.result)
          let a0106 = ''
          selectedOptions.forEach((e,index) => {
            if(index === selectedOptions.length - 1){
              a0106 = a0106 + e.label
            }else {
              a0106 = a0106 + e.label + '-'
            }
          })
          this.form.a0106 = a0106
        })
      }
    },
    onChangeTree(value, label, extra){
      console.log(value,label,extra)
      if(value[0]){
        if((this.beforeOrgId === '330300000000' && value[0] !== '330300000000') || (this.beforeOrgId !== '330300000000' && value[0] === '330300000000')){
          this.a0202SelectList = []
          this.form.permissionGroup = [{
            a0202: null,//人员类型
            objectType: 'router',//权限类型
            objectIds: [],//权限id
          }]
        }
        this.$http.post(getRoleParamsByOrg, {orgId: value[0]}).then(res => {
          this.a0202DictList = res.result
          this.beforeOrgId = value[0]
          if(value[0] === '330300000000'){
            this.length = 1
          }else {
            this.length = this.a0202DictList.length
          }
        })
      }else {
        this.a0202SelectList = []
        this.form.permissionGroup = [{
          a0202: null,//人员类型
          objectType: 'router',//权限类型
          objectIds: [],//权限id
        }]
      }
    },
    loadData(selectedOptions) {
      console.log(selectedOptions)
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;

      this.$http.post(getOrgOrUserInZzd, {searchOrg: targetOption.searchOrg,
        searchUser: targetOption.searchUser,organizationCode: targetOption.organizationCode}).then(res => {
        const list = res.result
        list.forEach(item =>{
          item.isLeaf = item.leaf
        })
        targetOption.loading = false;
        targetOption.children = list;
        this.options = [...this.options];
      })
    },
    removePermission(item){
      let index = this.form.permissionGroup.indexOf(item);
      if (index !== -1) {
        let a0202Index = -1
        this.a0202SelectList.forEach((e,eIndex) =>{
          if(e.index === index){
            a0202Index = eIndex
          }
        })
        if(a0202Index > -1){
          this.a0202SelectList.splice(a0202Index,1)
        }
        this.form.permissionGroup.splice(index, 1);
      }
    },
    lookForAllByKey(data = [],key,disabled) {
      for (let item of data) {
        if(item.key === key) {
          item.disabled = disabled
        }
        if (item.children && item.children.length) this.lookForAllByKey(item.children,key,disabled)
      }
    },
    lookForAllByParentKey(data = [],parentKey,disabled) {
      for (let item of data) {
        if(item.parentKey === parentKey) {
          item.disabled = disabled
        }
        if (item.children && item.children.length) this.lookForAllByParentKey(item.children,parentKey,disabled)
      }
    },
    handleChangeA0202(index,value){
      this.form.permissionGroup.forEach((item,index) =>{
        if(item.a0202){
          if(this.a0202SelectList[index]){
            this.a0202SelectList.splice(index,1,{index,value: item.a0202})
          }else {
            this.a0202SelectList.push({index,value: item.a0202})
          }
        }
      })
      if(['00','01'].indexOf(value) > -1){
        this.length = 1
        this.form.permissionGroup[index].disabled = true
        if(value === '01'){
          this.form.permissionGroup[index].objectIds = 'all'//所有模块权限
          this.form.permissionGroup[index].label = '所有业务模块权限'
        }else {
          this.form.permissionGroup[index].objectIds = 'allAndPartSystem'
          this.form.permissionGroup[index].label = '所有业务模块及部分系统权限'
        }
      }else if(['02','03','04'].indexOf(value) > -1){
        this.length = 2
        this.a0202SelectList.push({value: '01'})
        this.form.permissionGroup[index].disabled = undefined
        this.form.permissionGroup[index].objectIds = []
        this.$http.post(getOperateRouterTree, {userType:value}).then(res => {
          this.busiRouterTreeData = res.result
        })
      }
    },
    //禁用权限管理模块
    disabledPromissionRouter(){
      const busiRouterTreeData = JSON.parse(JSON.stringify(this.busiRouterTreeData))
      this.lookForAllByKey(busiRouterTreeData,'fdc300bf79bb429bb98fc3b820c38289',true)
      this.lookForAllByKey(busiRouterTreeData,'d13f472ea38444b495ac4d65dcc8cf55',true)
      this.busiRouterTreeData = busiRouterTreeData
    },
    addBusiRole(){
      this.form.permissionGroup.push({
        a0202: null,
        objectType: 'router',
        objectIds: [],
      })
    },
    getAllNodesForTreeByKey(data = [],arr = [],key,parentKey = null) {
      for (let item of data) {
        if(parentKey === null){
          if(item.key === key) {
            arr.push(item.key)
            if (item.children && item.children.length) this.getAllNodesForTreeByKey(item.children,arr,null,item.key)
          }else {
            if (item.children && item.children.length) this.getAllNodesForTreeByKey(item.children,arr,key)
          }
        }else {
          if(item.parentKey === parentKey) {
            arr.push(item.key)
            if (item.children && item.children.length) this.getAllNodesForTreeByKey(item.children,arr,null,item.key)
          }
        }
      }
      return arr
    },
    saveOrUpdate() {
      return new Promise((resolve, reject) => {
        this.$refs.userForm.validate(valid => {
          if (valid) {
            let flag = true
            if(!this.form.employeeCode){
              alert('请选择人员')
              flag = false
            }
            if(this.form.userOrgIds.length === 0){
              alert('请配置管理区域')
              flag = false
            }
            this.form.permissionGroup.forEach(e=>{
              if(!e.a0202){
                alert('请配置角色')
                flag = false
              }
              if(e.objectIds.length === 0){
                alert('请配置角色权限')
                flag = false
              }
            })
            if(flag === false){
              reject(false)
              return
            }
            const formData = JSON.parse(JSON.stringify(this.form))
            formData.userName = formData.employeeCode
            formData.permissionGroup.forEach(e=>{
              if(['00','01'].indexOf(e.a0202) > -1){
                e.objectIds = null
              }
            })
            resolve(formData)
          } else {
            reject(false)
          }
        });
      })

    },
  },
  computed: {

  },
  watch: {
    'a0202SelectList': {
      handler() {
        const a0202Select  = []
        this.a0202SelectList.forEach(e =>{
          a0202Select.push(e.value)
        })
        this.a0202DictList.forEach((item,index) =>{
          if(a0202Select.indexOf(item.dictKey) > -1){
            this.a0202DictList.splice(index,1,{dictKey: this.a0202DictList[index].dictKey,
              dictValue: this.a0202DictList[index].dictValue,status: '0'})
          }else {
            this.a0202DictList.splice(index,1,{dictKey: this.a0202DictList[index].dictKey,
              dictValue: this.a0202DictList[index].dictValue,status: '1'})
          }
        })
      },
      deep: true
    }
  }
};
</script>
<style lang="less" scoped>
.ant-form-item {
  margin-bottom: 5px;
}
.custom {
  .ant-form-item-children {
    span {
      width: 95%;
    }
  }
}
</style>
